package com.sw.paisong.controller;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sw.paisong.util.ServletUtils;
import com.sw.paisong.vo.JsonVO;
import com.sw.paisong.vo.ManagerVO;

@Controller
public class LoginController {

	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String loginPage() {
		logger.debug("get-login");
		return "login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public void doLogin(ManagerVO manager, HttpServletResponse response) {
		logger.debug("post-login");
		boolean isSuccess = true;
		String message = "";
		try {
			Subject currentUser = SecurityUtils.getSubject();
			UsernamePasswordToken token = new UsernamePasswordToken(manager.getAccount(),
					DigestUtils.md5Hex(manager.getPasswd()));
			currentUser.login(token);
			message = "登录成功！";
		} catch (Exception ex) {
			isSuccess = false;
			message = "账号或密码错误！";
			logger.error(ex.toString());
		}
		JsonVO jsonVO = new JsonVO();
		jsonVO.setSuccess(isSuccess);
		jsonVO.setMessage(message);
		ServletUtils.responseJson(response, jsonVO);
	}

	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	public void doLogout(HttpServletResponse response) {
		logger.debug("post-logout");
		boolean isSuccess = true;
		String message = "";
		try {
			SecurityUtils.getSubject().logout();
			message = "已登出！";
		} catch (Exception ex) {
			isSuccess = false;
			message = "登出失败";
			logger.error(ex.toString());
		}
		JsonVO jsonVO = new JsonVO();
		jsonVO.setSuccess(isSuccess);
		jsonVO.setMessage(message);
		ServletUtils.responseJson(response, jsonVO);
	}
	
}
